﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Logic;
using Entities;

namespace Presentation
{
	public enum Section
	{
		Library,
		Genre,
		List,
		Smartlist,
		Tag,
		Search
	}

	public partial class Main : Form
	{
        private TreeNode nodeSelected = new TreeNode();

		private List<Genre> genreCollection = new List<Genre>();
		private List<MovieList> listCollection = new List<MovieList>();
		private List<Smartlist> smartlistCollection = new List<Smartlist>();
		private List<Tag> tagCollection = new List<Tag>();

		private List<Movie> movieCollection = new List<Movie>();

		private Section section;

		public Section Section
		{
			get { return section; }
			set { section = value; }
		}

		public Main()
		{
			InitializeComponent();
		}

        internal void CloseQuickView()
        {
            quickInfoMovie.Visible = false;
            toolStripButtonShowQuickInfo.Image = Properties.Resources.OpenQuickInfo24;
            toolStripButtonShowQuickInfo.Text = "Show Quick Info";
            toolStripButtonShowQuickInfo.ToolTipText = "Show Quick Info";
        }

        public void GetInfo(Movie entity)
        {
            MovieInfo info = new MovieInfo(entity);
            if (info.ShowDialog() == DialogResult.OK)
            {
                movieCollection[objectListViewMovies.SelectedIndex] = info.Movie;
                objectListViewMovies.SelectedObjects[0] = info.Movie;
            }
            objectListViewMovies.RefreshSelectedObjects();
        }

        private void DeleteMovies()
        {
            int counter = 0;
            string confirmation = "";
            if (objectListViewMovies.SelectedObjects.Count == 1)
                confirmation = "Are you sure you want delete this movie?";
            else
                confirmation = "Are you sure you want delete these movies?";

            MovieBL bl = new MovieBL();
            if (MessageBox.Show(confirmation, "Deleting movies", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                for (int i = 0; i < objectListViewMovies.SelectedObjects.Count; i++)
                {
                    Movie entity = ((Movie)(objectListViewMovies.SelectedObjects[i]));
                    if (bl.Delete(entity))
                    {
                        movieCollection.Remove(entity);
                        counter++;
                    }
                }
            }
            if (counter == objectListViewMovies.SelectedObjects.Count)
                objectListViewMovies.RemoveObjects(objectListViewMovies.SelectedObjects);

            SetCounterLabel(movieCollection.Count, 0);
        }

		private void FillRenamingTitleFormats()
		{
			for (int i = 0; i < Logic.Properties.Settings.Default.RenamingTitleFormats.Count; i++)
			{
				ToolStripItem RenamingTitleFormatItem = new ToolStripMenuItem(Logic.Properties.Settings.Default.RenamingTitleFormats[i]);
				RenamingTitleFormatItem.Click += new EventHandler(RenamingTitleFormatItem_Click);
				toolStripMenuItemRenameMovie.DropDownItems.Add(RenamingTitleFormatItem);
			}
		}

		private object MovieRatingImageGetter(object row)
		{
			Movie m = (Movie)row;

			if (m.Rating == 0 || m.Rating == 5)
				return m.Rating;
			else
				return (5+m.Rating);
		}

		private void SetCounterLabel(int movieCounter, int selectedCounter)
		{
			string counterLabel = "{0} {1}";

			string moviecounter = "movies";

			if (movieCounter == 1)
				moviecounter = "movie";

			if (selectedCounter > 0)
				counterLabel += ", {2} selected";

			toolStripLabelMovieCounter.Text = String.Format(counterLabel, movieCounter, moviecounter, selectedCounter);
		}

		private void InitializeObjectListViewColumns()
		{
			olvColumnTitle.ImageGetter = delegate(object row)
			{
				if (objectListViewMovies.View == View.LargeIcon || objectListViewMovies.View == View.Tile)
				{
					/*string poster = "poster" + ((Movie)row).Id;

					if (!objectListViewMovies.LargeImageList.Images.ContainsKey(poster))
					{
						Stream stream = File.Open(((Movie)row).Poster, FileMode.Open, FileAccess.Read, FileShare.Delete);

						Image imagePoster = Image.FromStream(stream);
						objectListViewMovies.LargeImageList.Images.Add(poster, imagePoster);

						stream.Close();
					}*/

					string poster = ((Movie)row).Poster;

					Stream stream = File.Open(((Movie)row).Poster, FileMode.Open, FileAccess.Read, FileShare.Delete);

					Image imagePoster = Image.FromStream(stream);

					objectListViewMovies.LargeImageList.Images.Add(poster, imagePoster);

					stream.Close();

					return poster;
				}
				else
				{
					return MovieRatingImageGetter(row);
				}
			};

			olvColumnDuration.GroupKeyGetter = delegate(object row)
			{
				Movie movie = (Movie)row;

				string[] d = movie.VideoInfo.Duration.ToString().Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
				int duration = Convert.ToInt32(d[0]) * 3600 + Convert.ToInt32(d[1]) * 60 + Convert.ToInt32(d[2]);

				if (duration <= 3600)
					return -1;
				else
				{
					if (duration <= 7200)
						return 0;
					else
						return 1;
				}
			};

			olvColumnDuration.GroupKeyToTitleConverter = delegate(object o)
			{
				int duration = Convert.ToInt32(o);
				string title = "";

				switch (duration)
				{
					case -1:
						title = "Less than 1 hour";
						break;
					case 0:
						title = "Less than 2 hours";
						break;
					case 1:
						title = "More than 2 hours";
						break;
				}

				return title;
			};

			olvColumnRating.ImageGetter = new BrightIdeasSoftware.ImageGetterDelegate(this.MovieRatingImageGetter);
			olvColumnRating.GroupKeyToTitleConverter = delegate(object o)
			{
				int r = Convert.ToInt32(o);

				if (r == 1)
					return r + " star";

				return r + " stars";
			};
		}

		private void InitializeObjectListViewSettings()
		{
			InitializeObjectListViewColumns();

			objectListViewMovies.ShowGroups = false;
			objectListViewMovies.View = View.LargeIcon;
		}

		public void UpdateListViewItems(List<Movie> newmovieCollection)
		{
			if (section == Section.Genre && treeViewNavigator.SelectedNode == treeViewNavigator.Nodes[0])
			{
				movieCollection = newmovieCollection;

				labelListViewHeader.Text = "Last " + movieCollection.Count + " movies added";

				objectListViewMovies.SetObjects(movieCollection);


				SetCounterLabel(movieCollection.Count, 0);
			}
		}

		private void FillTreeView()
		{
			treeViewNavigator.Nodes.Clear();

			switch (section)
			{
				default:
				case Section.Library:
				case Section.Genre:
					GenreBL gbl = new GenreBL();
					genreCollection = gbl.List();

					TreeNode tAll = new TreeNode();
					tAll.Text = "All";
					tAll.Tag = "All";
					treeViewNavigator.Nodes.Add(tAll);

					foreach (Genre g in genreCollection)
					{
						TreeNode t = new TreeNode();
						t.Text = g.Name;
						t.Tag = g;

						treeViewNavigator.Nodes.Add(t);
					}

					if (treeViewNavigator.Nodes.Count > 0)
						treeViewNavigator.SelectedNode = treeViewNavigator.Nodes[0];

                    treeViewNavigator.LabelEdit = true;
					treeViewNavigator.CheckBoxes = false;
					treeViewNavigator.AllowDrop = true;
					break;
				case Section.List:
					ListBL lbl = new ListBL();
					listCollection = lbl.List();

					foreach (MovieList l in listCollection)
					{
						TreeNode t = new TreeNode();
						t.Text = l.Name;
						t.Tag = l;

						treeViewNavigator.Nodes.Add(t);
					}

                    treeViewNavigator.LabelEdit = true;
					treeViewNavigator.CheckBoxes = false;
					treeViewNavigator.AllowDrop = true;
					break;
				case Section.Smartlist:
					SmartlistBL sbl = new SmartlistBL();
					smartlistCollection = sbl.List();

					foreach (Smartlist s in smartlistCollection)
					{
						TreeNode t = new TreeNode();
						t.Text = s.Name;
						t.Tag = s;

						treeViewNavigator.Nodes.Add(t);
					}

                    treeViewNavigator.LabelEdit = true;
					treeViewNavigator.CheckBoxes = false;
					treeViewNavigator.AllowDrop = false;
					break;
				case Section.Tag:
					TagBL tbl = new TagBL();
					tagCollection = tbl.List();

					foreach (Tag tag in tagCollection)
					{
						TreeNode t = new TreeNode();
						t.Text = tag.Name;
						t.Tag = tag;

						treeViewNavigator.Nodes.Add(t);
					}

                    treeViewNavigator.LabelEdit = true;
					//treeViewNavigator.CheckBoxes = true;
					treeViewNavigator.AllowDrop = true;
					break;
			}
		}

		private void FillListView()
		{
			switch (section)
			{
				case Section.Library:
				case Section.Genre:
					if (treeViewNavigator.SelectedNode != null)
					{
						if (treeViewNavigator.SelectedNode.Tag.ToString() == "All")
						{
							MovieBL mobl = new MovieBL();
							movieCollection = mobl.GetLastMovies(10);

							labelListViewHeader.Text = "Last " + movieCollection.Count + " movies added";
						}
						else
						{
							Genre g = ((Genre)(treeViewNavigator.SelectedNode.Tag));

							GenreBL gbl = new GenreBL();
							movieCollection = gbl.GetMovies(g);

							labelListViewHeader.Text = g.Name+" movies";
						}
					}
					break;
				case Section.List:
					if (treeViewNavigator.SelectedNode != null)
					{
						MovieList l = ((MovieList)(treeViewNavigator.SelectedNode.Tag));

						ListBL lbl = new ListBL();
						movieCollection = lbl.GetMovies(l);

						labelListViewHeader.Text = "Movies in the List '" + l.Name + "'";
					}
					break;
				case Section.Smartlist:
					if (treeViewNavigator.SelectedNode != null)
					{
						Smartlist s = ((Smartlist)(treeViewNavigator.SelectedNode.Tag));

						SmartlistBL sbl = new SmartlistBL();

						movieCollection = sbl.GetMovies(s);

						labelListViewHeader.Text = "Movies in the Smartlist '"+s.Name+"'";
					}
					break;
				case Section.Tag:
					if (treeViewNavigator.SelectedNode != null)
					{
						Tag t = ((Tag)(treeViewNavigator.SelectedNode.Tag));

						TagBL tbl = new TagBL();
						movieCollection = tbl.GetMovies(t);

						labelListViewHeader.Text = "Movies with the tag '" + t.Name + "'";
					}
					break;
				case Section.Search:
					MovieBL mosebl = new MovieBL();
					movieCollection = mosebl.Search(toolStripTextBoxSearchBox.Text.Trim());
					labelListViewHeader.Text = "Results for '"+toolStripTextBoxSearchBox.Text.Trim()+"'";
					break;
				default:
					MovieBL mbl = new MovieBL();
					movieCollection = mbl.GetLastMovies(10);
					labelListViewHeader.Text = "Last 10 movies added";
					break;
			}

			InitializeObjectListViewColumns();

			objectListViewMovies.SetObjects(movieCollection);

			SetCounterLabel(movieCollection.Count, 0);
		}

		private void Main_Load(object sender, EventArgs e)
		{	
			if (SystemInformation.PrimaryMonitorSize.Width <= 800 && SystemInformation.PrimaryMonitorSize.Height <= 600)
			{
				this.Size = this.MinimumSize;
			}

			if (!Logic.Properties.Settings.Default.UpgradedDatabase)
			{
				TaskDialogUpgradeDatabase upgrade = new TaskDialogUpgradeDatabase();

				if (upgrade.ShowDialog() == DialogResult.Cancel)
				{
                    Close();
					Application.Exit();
				}
			}

			toolStripMain.Renderer = new CustomToolStripSystemRenderer(ToolStripBorderType.Bottom);
			toolStripMovies.Renderer = new CustomToolStripSystemRenderer(ToolStripBorderType.Bottom);
			toolStripStatusBar.Renderer = new CustomToolStripSystemRenderer(ToolStripBorderType.Top);

			section = Section.Genre;
			FillTreeView();

			FillRenamingTitleFormats();

			InitializeObjectListViewSettings();

			FillListView();

            objectListViewMovies.Select();
            if (objectListViewMovies.Items.Count > 0)
            {
                objectListViewMovies.Items[0].Selected = true;
            }
		}

		#region toolStripMain

		private void toolStripSplitButtonAdd_ButtonClick(object sender, EventArgs e)
		{
			objectListViewMovies.SuspendLayout();
			openFileDialogAddMovies.Title = "Select movies to add...";
			if (openFileDialogAddMovies.ShowDialog() == DialogResult.OK && openFileDialogAddMovies.FileNames.Length > 0)
			{
				List<Movie> moviestoadd = new List<Movie>();
				MovieBL mbl = new MovieBL();

				for (int i = 0; i < openFileDialogAddMovies.FileNames.Length; i++)
				{
					Movie obj = mbl.Create(new Video(openFileDialogAddMovies.FileNames[i]), false, false);
					moviestoadd.Add(obj);
				}

				string atitle = "{0} {1} {2} to add";

				if (openFileDialogAddMovies.FileNames.Length == 1)
					atitle = String.Format(atitle, openFileDialogAddMovies.FileNames.Length, "movie", "was selected");
				else
					atitle = String.Format(atitle, openFileDialogAddMovies.FileNames.Length, "movies", "were selected");

				TaskDialogAddMovieStep1 a = new TaskDialogAddMovieStep1(atitle);

				TaskDialogAddMovieStep2 b = new TaskDialogAddMovieStep2(moviestoadd);

				TaskDialogAddMovieStep3 c = new TaskDialogAddMovieStep3();

				VistaControls.TaskDialog.Results r = a.Show(this.Handle);

				if (r.CommonButton == VistaControls.TaskDialog.Result.OK)
				{
					if (r.RadioID == 1)
					{
						//Edit info
						if (b.ShowDialog() == DialogResult.OK)
						{
							moviestoadd = b.Movies;

							c.Movies = moviestoadd;

							if (c.ShowDialog() == DialogResult.OK)
							{
								UpdateListViewItems(mbl.GetLastMovies(moviestoadd.Count));
							}
						}
					}
					else
					{
						c.Movies = moviestoadd;

						if (c.ShowDialog() == DialogResult.OK)
						{
							UpdateListViewItems(mbl.GetLastMovies(moviestoadd.Count));
						}
					}
				}
			}
			objectListViewMovies.ResumeLayout();
		}

		private void toolStripMenuItemAddDirectory_Click(object sender, EventArgs e)
		{
			if (folderBrowserDialogAddFolder.ShowDialog() == DialogResult.OK && folderBrowserDialogAddFolder.SelectedPath != "")
			{
				objectListViewMovies.SuspendLayout();

				List<Movie> moviestoadd = new List<Movie>();

				MovieBL mbl = new MovieBL();

				string[] filenames = Directory.GetFiles(folderBrowserDialogAddFolder.SelectedPath);

				for (int i = 0; i < filenames.Length; i++)
				{
					if (!filenames[i].Contains(".avi") && !filenames[i].Contains(".divx") && !filenames[i].Contains(".mpg") && !filenames[i].Contains(".mpeg") && !filenames[i].Contains(".wmv") && !filenames[i].Contains(".mkv"))
						continue;

					Movie m = mbl.Create(new Video(filenames[i]), false, false);
					moviestoadd.Add(m);
				}

				if (moviestoadd.Count > 0)
				{
					TaskDialogAddMovieStep3 addmovies = new TaskDialogAddMovieStep3(moviestoadd);

					if (addmovies.ShowDialog() == DialogResult.OK)
					{
						UpdateListViewItems(mbl.GetLastMovies(moviestoadd.Count));
					}
				}

				objectListViewMovies.ResumeLayout();
			}
		}

		private void toolStripSplitButtonAddList_ButtonClick(object sender, EventArgs e)
		{
			TaskDialogAddList addlist = new TaskDialogAddList();
			if (addlist.ShowDialog() == DialogResult.OK)
			{
				if (section == Section.List)
				{
					FillTreeView();
				}
			}
		}

		private void toolStripMenuItemAddSmartlist_Click(object sender, EventArgs e)
		{
			TaskDialogAddSmartlist addsmartlist = new TaskDialogAddSmartlist();
			if (addsmartlist.ShowDialog() == DialogResult.OK)
			{
				if (section == Section.Smartlist)
				{
					FillTreeView();
				}
			}
		}

		private void toolStripButtonSettings_Click(object sender, EventArgs e)
		{
			Settings settings = new Settings();
			if (settings.ShowDialog() == DialogResult.OK)
				FillRenamingTitleFormats();
		}

		private void toolStripTextBoxSearchBox_Enter(object sender, EventArgs e)
		{
			if (((ToolStripTextBox)sender).Text == "Search for a movie")
			{
				((ToolStripTextBox)sender).Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
				((ToolStripTextBox)sender).ForeColor = SystemColors.WindowText;
				((ToolStripTextBox)sender).Text = "";
			}
		}

		private void toolStripTextBoxSearchBox_Leave(object sender, EventArgs e)
		{
			if (((ToolStripTextBox)sender).Text == "")
			{
				((ToolStripTextBox)sender).Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
				((ToolStripTextBox)sender).ForeColor = Color.LightGray;
				((ToolStripTextBox)sender).Text = "Search for a movie";
			}
		}

		private void toolStripTextBoxSearchBox_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == (char)13)
			{
				e.Handled = true;
				if (toolStripTextBoxSearchBox.Text.Trim() != "")
				{
					Section previous = section;
					section = Section.Search;
					FillListView();
					section = previous;
				}
			}
		}

		#endregion

		#region treeViewSections

		private void treeViewSections_AfterSelect(object sender, TreeViewEventArgs e)
		{
			switch (treeViewSections.SelectedNode.Index)
			{
				case 0:
				default:
					section = Section.Genre;
					linkLabelAdd.Visible = true;
					linkLabelAdd.Text = "Add genre";
					break;
				case 1:
					section = Section.List;
					linkLabelAdd.Visible = true;
					linkLabelAdd.Text = "Add list";
					break;
				case 2:
					section = Section.Smartlist;
					linkLabelAdd.Visible = true;
					linkLabelAdd.Text = "Add smartlist";
					break;
				case 3:
					section = Section.Tag;
					linkLabelAdd.Visible = false;
					break;
			}
			FillTreeView();
		}

		#endregion

		#region linkLabelAdd

		private void linkLabelAdd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			switch (section)
			{
				case Section.Genre:
					TaskDialogAddGenre addgenre = new TaskDialogAddGenre();
					if (addgenre.ShowDialog() == DialogResult.OK)
						FillTreeView();
					break;
				case Section.List:
					TaskDialogAddList addlist = new TaskDialogAddList();
					if (addlist.ShowDialog() == DialogResult.OK)
						FillTreeView();
					break;
				case Section.Smartlist:
					TaskDialogAddSmartlist addsmartlist = new TaskDialogAddSmartlist();
					if (addsmartlist.ShowDialog() == DialogResult.OK)
						FillTreeView();
					break;
			}
		}

		#endregion

		#region treeViewNavigator

		private void treeViewNavigator_AfterSelect(object sender, TreeViewEventArgs e)
		{
			FillListView();
        }

        private void objectListViewMovies_ItemDrag(object sender, ItemDragEventArgs e)
        {
            objectListViewMovies.DoDragDrop(objectListViewMovies.SelectedItems, DragDropEffects.All);
        }

        private void treeViewNavigator_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }

        private void treeViewNavigator_DragDrop(object sender, DragEventArgs e)
        {
            Point p = treeViewNavigator.PointToClient(new Point(e.X, e.Y));
            if (treeViewNavigator.GetNodeAt(p) != null)
            {
                TreeNode node = treeViewNavigator.GetNodeAt(p);

                string format = "{0} {1} {2} added to '{3}'";

                try
                {
                    for (int i = 0; i < objectListViewMovies.SelectedObjects.Count; i++)
                    {
                        switch (section)
                        {
                            case Presentation.Section.Genre:
                                Genre genre = (Genre)(node.Tag);
                                MovieBL mbl = new MovieBL();
                                if (mbl.AddGenre((Movie)(objectListViewMovies.SelectedObjects[i]), genre))
                                    ((Movie)(objectListViewMovies.SelectedObjects[i])).Genres.Add(genre);
                                break;
                            case Presentation.Section.List:
                                MovieList list = (MovieList)(node.Tag);
                                ListBL lbl = new ListBL();
                                lbl.AddMovie(list, (Movie)(objectListViewMovies.SelectedObjects[i]));
                                break;
                            case Presentation.Section.Tag:
                                Tag tag = (Tag)(node.Tag);
                                TagBL tbl = new TagBL();
                                if (tbl.AddMovie(tag, (Movie)(objectListViewMovies.SelectedObjects[i])))
                                    ((Movie)(objectListViewMovies.SelectedObjects[i])).Tags.Add(tag);
                                break;
                        }
                    }

                    if (objectListViewMovies.SelectedObjects.Count == 1)
                    {
                        format = String.Format(format, new object[] { "1", "movie", "was", node.Text });
                    }
                    else
                        format = String.Format(format, new object[] { objectListViewMovies.SelectedObjects.Count, "movies", "were", node.Text });

                    MessageBox.Show(format, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    objectListViewMovies.RefreshSelectedObjects();
                }
                catch (Exception ex)
                {
                    //log
                }
            }
        }

        private void treeViewNavigator_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            nodeSelected = treeViewNavigator.GetNodeAt(new Point(e.X, e.Y));
        }

		#endregion

		#region toolStripMovies

		private void toolStripButtonPlay_Click(object sender, EventArgs e)
		{
			MovieBL mbl = new MovieBL();
			mbl.Play((Movie)(objectListViewMovies.SelectedObjects[0]));
		}

		private void toolStripButtonGetInfo_Click(object sender, EventArgs e)
		{
            GetInfo((Movie)(objectListViewMovies.SelectedObjects[0]));
		}

		private void toolStripButtonDelete_Click(object sender, EventArgs e)
		{
            DeleteMovies();
		}

		#endregion

		#region objectListViewMovies

		private void objectListViewMovies_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (objectListViewMovies.SelectedItems.Count > 0)
			{
				toolStripButtonPlay.Enabled = true;
				toolStripButtonGetInfo.Enabled = true;
				toolStripButtonDelete.Enabled = true;
				toolStripButtonSocial.Enabled = true;

                quickInfoMovie.FillData((Movie)(objectListViewMovies.SelectedObjects[0]));
			}
			else
			{
				toolStripButtonPlay.Enabled = false;
				toolStripButtonGetInfo.Enabled = false;
				toolStripButtonDelete.Enabled = false;
				toolStripButtonSocial.Enabled = false;
			}

			SetCounterLabel(movieCollection.Count, objectListViewMovies.SelectedItems.Count);
		}

		private void objectListViewMovies_MouseClick(object sender, MouseEventArgs e)
		{
			switch(e.Button)
			{
				case MouseButtons.Left:
					if (e.Clicks == 2)
					{
						if (objectListViewMovies.SelectedObject != null)
						{
							MovieBL mbl = new MovieBL();
							mbl.Play((Movie)(objectListViewMovies.SelectedObject));
						}
					}
					break;
			}
		}

        private void objectListViewMovies_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter) || Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void objectListViewMovies_KeyDown(object sender, KeyEventArgs e)
        {
            if (objectListViewMovies.SelectedObjects.Count > 0)
            {
                switch (e.KeyCode)
                {
                    case Keys.Enter:
                        MovieBL mbl = new MovieBL();
                        mbl.Play((Movie)(objectListViewMovies.SelectedObjects[0]));
                        break;
                    case Keys.I:
                        if (e.Control)
                        {
                            MovieInfo info = new MovieInfo((Movie)(objectListViewMovies.SelectedObjects[0]));
                            if (info.ShowDialog() == DialogResult.OK)
                            {
                                movieCollection[objectListViewMovies.SelectedIndex] = info.Movie;
                                objectListViewMovies.SelectedObjects[0] = info.Movie;
                            }
                            objectListViewMovies.RefreshSelectedObjects();
                        }
                        break;
                    case Keys.Delete:
                        DeleteMovies();
                        break;
                    case Keys.F5:
                        FillListView();
                        break;
                }
            }
        }

		#endregion

        #region toolStripStatusBar

        private void toolStripButtonShowQuickInfo_Click(object sender, EventArgs e)
        {
            if (quickInfoMovie.Visible == true)
            {
                quickInfoMovie.Visible = false;
                toolStripButtonShowQuickInfo.Image = Properties.Resources.OpenQuickInfo24;
                toolStripButtonShowQuickInfo.Text = "Show Quick Info";
                toolStripButtonShowQuickInfo.ToolTipText = "Show Quick Info";
            }
            else
            {
                quickInfoMovie.Visible = true;
                toolStripButtonShowQuickInfo.Image = Properties.Resources.CloseQuickInfo24;
                toolStripButtonShowQuickInfo.Text = "Hide Quick Info";
                toolStripButtonShowQuickInfo.ToolTipText = "Hide Quick Info";
            }
        }

		private void toolStripButtonShowGroups_CheckStateChanged(object sender, EventArgs e)
		{
			objectListViewMovies.ShowGroups = toolStripButtonShowGroups.Checked;
		}

		private void toolStripMenuItemLargeView_Click(object sender, EventArgs e)
		{
			toolStripMenuItemLargeView.Visible = false;
			toolStripMenuItemDetailsView.Visible = true;
			toolStripMenuItemTileView.Visible = true;

			objectListViewMovies.ShowGroups = false;

			toolStripButtonShowGroups.Enabled = false;

			objectListViewMovies.SelectColumnsOnRightClick = false;

			objectListViewMovies.View = View.LargeIcon;

			toolStripDropDownButtonView.Image = toolStripMenuItemLargeView.Image;
		}

		private void toolStripMenuItemDetailsView_Click(object sender, EventArgs e)
		{
			toolStripMenuItemLargeView.Visible = true;
			toolStripMenuItemDetailsView.Visible = false;
			toolStripMenuItemTileView.Visible = true;

			objectListViewMovies.ShowGroups = true;

			toolStripButtonShowGroups.Enabled = toolStripButtonShowGroups.Checked;

			objectListViewMovies.SelectColumnsOnRightClick = true;

			objectListViewMovies.View = View.Details;

			toolStripDropDownButtonView.Image = toolStripMenuItemDetailsView.Image;
		}

		private void toolStripMenuItemTileView_Click(object sender, EventArgs e)
		{
			toolStripMenuItemLargeView.Visible = true;
			toolStripMenuItemDetailsView.Visible = true;
			toolStripMenuItemTileView.Visible = false;

			objectListViewMovies.ShowGroups = toolStripButtonShowGroups.Checked;

			toolStripButtonShowGroups.Enabled = true;

			objectListViewMovies.SelectColumnsOnRightClick = false;

			objectListViewMovies.View = View.Tile;

			toolStripDropDownButtonView.Image = toolStripMenuItemTileView.Image;
		}

		#endregion

        #region contextMenuStripMovies

        private void toolStripMenuItemPlay_Click(object sender, EventArgs e)
        {
            MovieBL mbl = new MovieBL();
            mbl.Play((Movie)(objectListViewMovies.SelectedObjects[0]));
        }

        private void toolStripMenuItemGetInformation_Click(object sender, EventArgs e)
        {
            MovieInfo info = new MovieInfo((Movie)(objectListViewMovies.SelectedObjects[0]));
            if (info.ShowDialog() == DialogResult.OK)
            {
                movieCollection[objectListViewMovies.SelectedIndex] = info.Movie;
                objectListViewMovies.SelectedObjects[0] = info.Movie;
            }
            objectListViewMovies.RefreshSelectedObjects();
        }

        private void toolStripMenuItemDelete_Click(object sender, EventArgs e)
        {
            DeleteMovies();
        }

		private void contextMenuStripMovies_Opening(object sender, CancelEventArgs e)
		{
			if (objectListViewMovies.SelectedItems.Count == 0)
				e.Cancel = true;
		}

		private void RenamingTitleFormatItem_Click(object sender, EventArgs e)
		{
			MovieBL mbl = new MovieBL();
			mbl.RenameTitle((Movie)(objectListViewMovies.SelectedObjects[0]), ((ToolStripItem)sender).Text);

			objectListViewMovies.RefreshSelectedObjects();
		}

		private void toolStripMenuItemRenameFile_Click(object sender, EventArgs e)
		{
			TaskDialogRenameFile renamefile = new TaskDialogRenameFile((Movie)(objectListViewMovies.SelectedObjects[0]));

			if (renamefile.ShowDialog() == DialogResult.OK)
			{
				objectListViewMovies.RefreshSelectedObjects();
			}
		}

		private void toolStripMenuItemSet1Star_Click(object sender, EventArgs e)
		{
			Movie entity = ((Movie)(objectListViewMovies.SelectedObjects[0]));
			entity.Rating = 1;

			MovieBL mbl = new MovieBL();
			mbl.UpdateRating(entity);
		}

		private void toolStripMenuItemSet2Stars_Click(object sender, EventArgs e)
		{
			Movie entity = ((Movie)(objectListViewMovies.SelectedObjects[0]));
			entity.Rating = 2;

			MovieBL mbl = new MovieBL();
			mbl.UpdateRating(entity);
		}

		private void toolStripMenuItemSet3Stars_Click(object sender, EventArgs e)
		{
			Movie entity = ((Movie)(objectListViewMovies.SelectedObjects[0]));
			entity.Rating = 3;

			MovieBL mbl = new MovieBL();
			mbl.UpdateRating(entity);
		}

		private void toolStripMenuItemSet4Stars_Click(object sender, EventArgs e)
		{
			Movie entity = ((Movie)(objectListViewMovies.SelectedObjects[0]));
			entity.Rating = 4;

			MovieBL mbl = new MovieBL();
			mbl.UpdateRating(entity);
		}

		private void toolStripMenuItemSet5Stars_Click(object sender, EventArgs e)
		{
			Movie entity = ((Movie)(objectListViewMovies.SelectedObjects[0]));
			entity.Rating = 5;

			MovieBL mbl = new MovieBL();
			mbl.UpdateRating(entity);
		}

		private void toolStripMenuItemReplaceFiles_Click(object sender, EventArgs e)
		{
			openFileDialogAddMovies.Title = "Select the new location of this movie";
			if (openFileDialogAddMovies.ShowDialog() == DialogResult.OK && openFileDialogAddMovies.FileNames.Length > 0)
			{
				MovieBL mbl = new MovieBL();
				if (mbl.ChangeLocation((Movie)(objectListViewMovies.SelectedObjects[0]), openFileDialogAddMovies.FileNames))
					MessageBox.Show("Location changed successfully", "Location changed", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
		}

		private void toolStripMenuItemMoveTo_Click(object sender, EventArgs e)
		{
			if (folderBrowserDialogAddFolder.ShowDialog() == DialogResult.OK && folderBrowserDialogAddFolder.SelectedPath != "")
			{
				MovieBL mbl = new MovieBL();
				mbl.MoveTo((Movie)(objectListViewMovies.SelectedObjects[0]), folderBrowserDialogAddFolder.SelectedPath);
			}
		}

		private void toolStripMenuItemShowInExplorer_Click(object sender, EventArgs e)
		{
			MovieBL mbl = new MovieBL();
			mbl.ShowInExplorer((Movie)(objectListViewMovies.SelectedObjects[0]));
		}

		#endregion

		private void Main_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (Logic.Properties.Settings.Default.DeletePostersAtClose)
			{
				try
				{
					foreach (string poster in Logic.Properties.Settings.Default.PostersToDelete)
						if (File.Exists(poster))
							File.Delete(poster);

					Logic.Properties.Settings.Default.Save();
				}
				catch (Exception ex)
				{
					//log
				}
			}
        }

        private void contextMenuStripNavigator_Opening(object sender, CancelEventArgs e)
        {
            if (treeViewNavigator.SelectedNode == null || (section == Presentation.Section.Genre && nodeSelected == treeViewNavigator.Nodes[0]))
                e.Cancel = true;
        }

        private void toolStripMenuItemEditItem_Click(object sender, EventArgs e)
        {
            nodeSelected.BeginEdit();
        }

        private void toolStripMenuItemDeleteItem_Click(object sender, EventArgs e)
        {
            switch (section)
            {
                case Presentation.Section.Genre:
                    if (MessageBox.Show("Do you really want to delete '" + nodeSelected.Text + "'?", "Deleting genre", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        GenreBL gbl = new GenreBL();
                        if (gbl.Delete((Genre)(nodeSelected.Tag)))
                            MessageBox.Show("Genre deleted successfully", "Genre deleted", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    break;
                case Presentation.Section.List:
                    if (MessageBox.Show("Do you really want to delete '" + nodeSelected.Text + "'?", "Deleting list", MessageBoxButtons.YesNo, MessageBoxIcon.Question)==System.Windows.Forms.DialogResult.Yes)
                    {
                        ListBL lbl = new ListBL();
                        if(lbl.Delete((MovieList)(nodeSelected.Tag)))
                            MessageBox.Show("List deleted successfully", "List deleted", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    break;
                case Presentation.Section.Smartlist:
                    if (MessageBox.Show("Do you really want to delete '" + nodeSelected.Text + "'?", "Deleting smartlist", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        SmartlistBL sbl = new SmartlistBL();
                        if(sbl.Delete((Smartlist)(nodeSelected.Tag)))
                            MessageBox.Show("Smartlist deleted successfully", "Smartlist deleted", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    break;
                case Presentation.Section.Tag:
                    if (MessageBox.Show("Do you really want to delete '" + nodeSelected.Text + "'?", "Deleting tag", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        TagBL tbl = new TagBL();
                        if(tbl.Delete((Tag)(nodeSelected.Tag)))
                            MessageBox.Show("Tag deleted successfully", "Tag deleted", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    break;
            }
            FillTreeView();
        }

        private void treeViewNavigator_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (e.Label.Trim() != "")
            {
                switch (section)
                {
                    case Presentation.Section.Genre:
                        Genre g = ((Genre)(nodeSelected.Tag));
                        g.Name = e.Label;

                        GenreBL gbl = new GenreBL();
                        gbl.Update(g);
                        break;
                    case Presentation.Section.List:
                        MovieList l = ((MovieList)(nodeSelected.Tag));
                        l.Name = e.Label;

                        ListBL lbl = new ListBL();
                        lbl.Update(l);
                        break;
                    case Presentation.Section.Smartlist:
                        Smartlist s = ((Smartlist)(nodeSelected.Tag));
                        s.Name = e.Label;

                        SmartlistBL sbl = new SmartlistBL();
                        sbl.UpdateName(s);
                        break;
                    case Presentation.Section.Tag:
                        Tag t = ((Tag)(nodeSelected.Tag));
                        t.Name = e.Label;

                        TagBL tbl = new TagBL();
                        tbl.Update(t);
                        break;
                }
            }
        }
    }
}